package com.ruoyi.framework.mq.RabbitMQ;

import com.ruoyi.common.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 发送消息工具类
 */
@Component
public class RabbitMQMsgUtil {
    private static final Logger log=LoggerFactory.getLogger(RabbitMQMsgUtil.class);
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     *  延时队列插件发送
     * @param exchange   交换机
     * @param routingKey 路由key
     * @param pojo   消息体 String类型
     * @param expiration  过期时间，单位毫秒 Integer 类型
     */
    public void sendMessage(String exchange,String routingKey,MessagePojo pojo, Integer expiration){
        if (pojo != null){

            CorrelationData correlationData = new CorrelationData(pojo.getId());

            rabbitTemplate.convertAndSend(exchange,routingKey,pojo.getMsg(),
                    message -> {
                        message.getMessageProperties().setDelay(expiration);
                        return message;
                    },correlationData);
            log.info("消息发送时间：{}", DateUtils.getNowDate());
        }else {
            log.error("消息内容为空");
        }
    }

    /**
     *
     * @param exchange   交换机
     * @param routingKey 路由key
     * @param pojo   消息体 String类型
     *
     */
    public void sendMessage(String exchange,String routingKey,MessagePojo pojo){
        if (pojo != null){
            CorrelationData correlationData = new CorrelationData(pojo.getId());
            rabbitTemplate.convertAndSend(exchange,routingKey,pojo.getMsg(),correlationData);
            log.info("消息发送时间：{}", DateUtils.getNowDate());
        }else {
            log.error("消息内容为空");
        }
    }
}
